<template>
  <t-dialog
    :width="width ? width : '50%'"
    :visible="showDialog"
    @confirm="handleConfirm"
    @close="handleCancel"
    @cancel="handleCancel"
    preventScrollThrough
    placement="center"
  >
    <template #header>{{ mode == "new" ? "新增" : mode == "edit" ? "编辑" : mode == "view" ? "查看" : "" }} </template>
    <t-form ref="formInstance" :data="pageData.formData" :rules="pageData.formRules" :disabled="pageData.readOnly">
      <t-form-item label="备注" name="customerRemark" :labelWidth="60">
        <t-textarea v-if="!pageData.readOnly" v-model="pageData.formData.customerRemark" :autosize="{ minRows: 8 }" />
        <div v-else class="form__text">{{ pageData.formData.customerRemark }}</div>
      </t-form-item>
    </t-form>
  </t-dialog>
</template>

<script lang="tsx" setup>
// 框架和组件库
import { reactive, ref, toRaw } from "vue";
import type { FormInstanceFunctions } from "tdesign-vue-next";

const props = defineProps(["width", "showDialog", "mode", "editFormData"]);
const emits = defineEmits(["onCancel", "onConfirm"]);

const formInstance = ref<FormInstanceFunctions | null>(null);

const pageData = reactive({
  readOnly: false,
  formData: {} as Record<string, any>,
  formRules: {
    customerRemark: [{ required: true, message: "请输入备注", type: "error" }]
  }
});
const handleCancel = () => {
  emits("onCancel");
};

const handleConfirm = async () => {
  const validateResult = await formInstance?.value?.validate();
  if (validateResult === true) {
    emits("onConfirm", toRaw(pageData.formData));
  }
};

if (props.editFormData) {
  pageData.formData = toRaw(props.editFormData);
}

if (props.mode === "view") {
  pageData.readOnly = true;
}
</script>
